<template>
  <div class="app-container">
    <!-- 用户信息展示 -->
    <!-- 切换显示信息开关 -->
    <el-switch
      style="display: block"
      v-model="discription"
      active-color="#1366ce"
      inactive-color="#ff4949"
      active-text="详细信息"
      inactive-text='基本信息'
      align='right'>
    </el-switch>
    <br>
    <!-- {{ course_list }} -->
    <!-- 课程列表 -->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="course_list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column align="center" type='index' label="序号" width="55">
      </el-table-column>
      <el-table-column type="expand">
      <template slot-scope="props">
        <!-- 章节信息 -->
        <el-form label-position="left" inline class="demo-table-expand">
          <div style='margin-left:300px' v-for="(section,index) in props.row.sections" :key='index'>
          <el-form-item :label="'第'+(index+1)+'节'">
            <span>{{ section.section_name }}</span>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <!-- 查看视频，直接连接到七牛云即可 -->
            <!-- {{ section.video }} -->
            <a :href="'http://q9j3oo8by.bkt.clouddn.com/' + section.video" target="_blank"><el-button size="mini">查看视频</el-button></a>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <!-- 上传视频，不需要预览，直接上传到七牛云即可 -->
            <input type="file" id="btn_file" style="display:none" @change="upload_qiniu">
            <el-button @click='upload_video(section.id)' type="primary" size="mini">上传视频</el-button>
          </el-form-item>
          </div>
          上传进度：{{fileload}}
        </el-form>
      </template>
    </el-table-column>
      <el-table-column label="头图" width='200px' align="center">
        <template slot-scope="scope">
            <el-row class="demo-avatar demo-basic">
              <el-col :span="12">
                <div class="demo-basic--circle">
                  <div class="block">
                    <el-image
                      style="width: 180px; height:102px"
                      :src="get_photo(scope.row.img)"
                      :fit="'fit'"></el-image>
                    
                    </div>
                </div>
              </el-col>
            </el-row>
        </template>
      </el-table-column>
      <el-table-column label="id" width='70px' align="center" prop='id'>
      </el-table-column>
      
      <el-table-column label="标题" align="center" prop='name'>
      </el-table-column>
      <el-table-column label="作者" v-if="discription" width='140px' align="center" prop='author'>
      </el-table-column>
      <el-table-column label="种类" v-if="discription" align="center" prop='category' width='90px'>
      </el-table-column>
      <el-table-column label="收藏数" v-if="discription" align="center" prop='collect_num' width='90px'>
      </el-table-column>
      <el-table-column label="价格" v-if="discription" align="center" prop='price' width='90px'>
      </el-table-column>
      <el-table-column label="状态" v-if="discription" align="center" width='90px'>
        <template slot-scope="scope">
          {{ scope.row.is_online|online }}
        </template>
      </el-table-column>
      <el-table-column label="描述" v-if="!discription" align="center" prop='desc'>
      </el-table-column>
      <el-table-column label="操作" align="center" width='200px' prop=''>
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
      </el-table-column>
      <el-table-column align="center" label="注册日期" width='200px'>
        <template slot-scope="scope">
          <i class="el-icon-time" />{{ scope.row.create_time|date_time }}
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-button type="primary" :disabled="amount" round @click='del_multi'>批量删除</el-button>
    
    <el-button @click="toggleSelection()" round>取消选择</el-button>
    <br>
    <el-pagination
      background
      :hide-on-single-page='true'
      layout="prev, pager, next"
      align='center'
      :total="total"
      @current-change='change_page'
      >
    </el-pagination>

    <!-- 修改课程信息的表单 -->
    <el-dialog title="修改课程信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="课程名称" :label-width="formLabelWidth">
          <el-input v-model="form.name"
            maxlength="20"
            show-word-limit 
            autocomplete="off">
          </el-input>
        </el-form-item>
        <el-form-item 
        label="标签" 
        :label-width="formLabelWidth">
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedTags" @change="handleCheckedTagsChange">
          <el-checkbox v-for="tag in tag_list" :label="tag.id" :key="tag.id">{{tag.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="头图">
        <input type="file" @change="up_qiniu">
        </el-form-item>
       

        <el-form-item label="种类" :label-width="formLabelWidth">
          <el-select v-model="form.category" placeholder="请选择种类">
            <el-option label="免费" value="免费"></el-option>
            <el-option label="限免" value="限免"></el-option>
            <el-option label="会员" value="会员"></el-option>
            <el-option label="训练营" value="训练营"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="价格"
          :rules="[
            { required: true, message: '价格不能为空'},
            { type: 'number', message: '价格必须是数字'}
          ]"
        >
          <el-input type="age" v-model.number="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否上架" :label-width="formLabelWidth">
          <el-radio-group v-model="form.is_online">
            <el-radio-button label="0">即将上架</el-radio-button>
            <el-radio-button label="1">已上架</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-form-item label="描述">
            <el-input type="textarea" v-model="form.desc" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item label="创建日期" :label-width="formLabelWidth">
          <div class="block">
            <el-date-picker
              v-model="form.create_time"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit_put" :loading="submit_loading">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { tags_get, get_course_all, course_info_put, course_info_delete ,get_uptoken,add_video_post,get_video} from "../axios_api/api"
import { getList } from '@/api/table'
import { constants } from 'zlib';

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      // 七牛云上传凭证
      uptoken:'',
      // 进度条
      fileload:'',
      // 七牛云key
      key:'',
      // 视频连接
      videosrc:'',
      // 标签列表
      checkedTags:[],
      tag_list:[],
      sectionForm: {
          sections: [{
            value: ''
          }]
        },
      // 批处理开关
      amount:true,
      list: null,
      listLoading: true,
      discription: true,
      // 用户列表变量
      course_list: [],
      // vip变量
      vipdatas: {},
      // 管理员名
      username: localStorage.getItem("username"),
      // 弹窗变量
      UpdateUser: false,
      AddUser: false,
      DeleteUser: false,
      datas: {},
      // 分页
      total: 0,
      page: 1,
      size: 10,
      multipleSelection: [],
      // 表单开关
      dialogFormVisible: false,
      // 表单数据
      form: {
          name: '',
          category: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
      // 表单宽度
      formLabelWidth:"400",
      // 表单加载动态效果
      submit_loading: false
    }
  },
  mounted() {
    this.get_course_list();
    this.get_uptoken();
  },
  methods: {
    // 标签复选框
    handleCheckAllChange(val) {
      this.checkedTags = val ? tagOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedTagsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tag_list.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tag_list.length;
      console.log(this.checkedTags)
    },
    //批量删除
    del_multi(){
      this.submit_loading = true
      var li = []
      for(let i=0;i<this.multipleSelection.length;i++){
        li.push(this.multipleSelection[i].id)
      }
      var params = {id_list:String(li), method:'delete'}
      course_info_delete(params).then(resp=>{
        this.$message(resp)
        this.get_course_list()
        this.submit_loading = false
      })

    },
    // 删除
    handleDelete(index,data){
      this.submit_loading = true
      var params = {id_list:String(data.id), method:'delete'}
      console.log(params)
      course_info_delete(params).then(resp=>{
        this.$message(resp)
        this.get_course_list()
        this.submit_loading = false
      })
      
    },
    // 提交修改
    submit_put(){
      this.submit_loading = true
      this.form['tags'] = this.checkedTags
      course_info_put(this.form).then(resp=>{
        this.$message(resp.message)
        // 重新请求数据
        this.get_course_list()
        this.submit_loading = false
      })
      this.dialogFormVisible = false
    },
    // 查看视频
    show_video(video){
      console.log(video)
      // var params = {sid:sid}
      // console.log(params)
      // get_video(params).then(res=>{
      //   console.log(res)
      //   return 'http://q9j3oo8by.bkt.clouddn.com/' + res.video
      //   // this.videosrc = 'http://q9j3oo8by.bkt.clouddn.com/' + res.video
      //   // window.location.href = 'http://q9j3oo8by.bkt.clouddn.com/' + res.video
      // })
    },
    // 获取七牛云凭证
    get_uptoken(){
        get_uptoken().then(res=>{
          this.uptoken = res.token
        })
    },
    // 课程头图上传七牛
    up_qiniu(e){
      // 获取文件对象
      let file = e.target.files[0];
      // 声明变量
      let param = new FormData();
      // 将上传凭证添加参数
      param.append('token',this.uptoken);
      // 添加文件
      param.append('file',file);
      // 定制化axios
      const axios_qiniu = this.axios.create({withCredentials:false});
      // 发送请求
      axios_qiniu({
        method:'POST',
        url:'http://up-z1.qiniu.com',
        data:param,
        timeout:30000
      }).then(res=>{
        console.log(res.key)
        this.form.img = res.data.key
      })
    },
    // 上传七牛
	  upload_qiniu(e){
      // 获取文件对象
      let file = e.target.files[0];
      // 声明变量
      let param = new FormData();
      // 将上传凭证添加参数
      param.append('token',this.uptoken);
      // 添加文件
      param.append('file',file);
      // 定制化axios
      const axios_qiniu = this.axios.create({withCredentials:false});
      // 发送请求
      axios_qiniu({
        method:'POST',
        url:'http://up-z1.qiniu.com',
        data:param,
        timeout:30000,
			// 上传进度
			onUploadProgress:(e)=>{
				// 计算
				var com = (e.loaded / e.total);
				// 判断
				if(com < 1){
					this.fileload = (com * 100).toFixed(2) + '%' 
				}
			},
		}).then(res=>{
			console.log(res)
      this.key = res.data.key
			// 请求结束
      this.fileload = '100%'
      this.upload_video()
		}) 
	},

    // 上传视频
    upload_video(sid){
      if(this.key == ''){
        localStorage.setItem('mid',sid)
        document.getElementById('btn_file').click();
      }else{
        var data = {key:this.key, sid: localStorage.getItem('mid')}
        add_video_post(data).then(res=>{         
                alert(res.msg)
                this.$router.go(0);
            })
      }
      
    },
    // 修改课程信息
    handleEdit(index,data){
      this.dialogFormVisible = true
      this.form = data
      // 获取本课程标签
      tags_get().then(resp=>{
        this.tag_list = resp.data
        console.log(this.tag_list)
        var params = {cid:data.id}
        tags_get(params).then(resp=>{
          this.checkedTags = resp.data
          console.log(this.checkedTags)
        })
      })
    },
    // 动态拼接头图
    get_photo(img){
      if(img=='course.jpg'){
        return require('../../../static/img/course.jpg')
      }else{
        // return img 返回七牛云图片链接
        return "http://q9j3oo8by.bkt.clouddn.com/" + img
      }
    },
    // 换页
    change_page(val){
      this.page = val
      this.get_course_list()
    },
    // 获取多选值
    handleSelectionChange(val) {
      this.multipleSelection = val;
        console.log(this.multipleSelection)
      if(this.multipleSelection.length==0){
        this.amount = true
      }else{
        this.amount = false
      }
    },
    // 取消选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 获取课程列表
    get_course_list() {
      this.listLoading = true
      get_course_all({ "page": this.page, "size": this.size }).then(resp => {
      
        this.total = resp.total
        console.log(this.total)
        // 将用户传入userlist列表中
        this.course_list = resp.data;
        this.listLoading = false

      })
    },
  },
  filters:{
    date_time(value){
      return value.split('T').join(' ').split('.')[0]
    },
    online(value){
      if(value=='0'){
        return '即将上架'
      }else{
        return '已上架'
      }
    }
  }
}
</script>

